package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 查询地址
     * @return
     */
    @Override
    public List<Address> findAll() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);
        return addressList;
    }

    /**
     * 添加地址
     * @param address
     */
    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    /**
     * 更新地址
     * @param address
     */
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    /**
     * 根据id删除地址
     * @param ids
     */
    @Override
    public void delete(Long ids) {
        addressMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 设置默认地址
     * @param address
     */
    @Override
    public void updateDefault(Address address) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault,1);
        //查询
        Address addressDefault = addressMapper.selectOne(wrapper);
        if (addressDefault!=null){
            //修改用户已经设置的默认地址
            addressDefault.setIsDefault(0);
            //更新地址
            addressMapper.updateById(addressDefault);
        }
        //设置要定义第默认地址
        address.setIsDefault(1);
        //设置更新条件
        LambdaQueryWrapper<Address> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Address::getId,address.getId());
        addressMapper.update(address,wrapper1);


    }

    /**
     * 查询当前用户的默认地址
     * @return
     */
    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId()).eq(Address::getIsDefault,1);
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }


}
